package com.docwei.thansgank.fragment.fuli;

import com.docwei.thansgank.callback.ResultBean;
import com.docwei.thansgank.fragment.IPullDataRequestListener;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by tobo on 17/8/1.
 */

public class FuliModel implements IFuliModel {
    @Override
    public void pullFuliData(final IPullDataRequestListener<ResultBean> iPullDataRequestListener) {
        String url = "http://gank.io/api/data/福利/20/1";
        OkHttpUtils
                .get()
                .url(url)
                .id(100)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onAfter(int id) {
                        if (iPullDataRequestListener != null) {
                            iPullDataRequestListener.after();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (e.getMessage() == null) {
                            return;
                        }
                        if (iPullDataRequestListener != null) {
                            iPullDataRequestListener.pullDataError(e.getMessage());
                        }
                    }

                    @Override
                    public void onBefore(Request request, int id) {
                        if (iPullDataRequestListener != null) {
                            iPullDataRequestListener.before();
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        ResultBean bean = gson.fromJson(response, ResultBean.class);
                        if (bean == null) {
                            if (iPullDataRequestListener != null) {
                                iPullDataRequestListener.pullDataError("返回数据异常");
                                return;
                            }
                        }
                        if (iPullDataRequestListener != null) {
                            iPullDataRequestListener.pullDataSuccess(bean);
                        }
                    }
                });
    }
}
